var http = require('http');
var https = require('https');
var fs = require('fs');
var childProcess = require('child_process');
const path = require('path');



var socketIo = require('socket.io');
var serveIndex = require('serve-index');
var express = require('express');
var app = express();


//node执行cmd指令
var cmd = 'ipconfig';
childProcess.exec(cmd, function (error, stdout, stderr) {
	// console.log("error:"+error);
	//console.log("stdout:" + stdout);
	//console.log("stderr:"+stderr);
});

//启动http服务

var http_server = http.createServer(app);
http_server.listen(4500, () => {
	console.warn('http :4500');
});


//启动https服务

var filePathKey = path.join(__dirname, './cert/1557605_www.learningrtc.cn.key')
var filePathCert = path.join(__dirname, './cert/1557605_www.learningrtc.cn.pem')
var options = {
	key: fs.readFileSync(filePathKey),
	cert: fs.readFileSync(filePathCert)
}
var https_server = https.createServer(options, app);
https_server.listen(4400, () => {
	console.warn('https :4400');
});


app.get("/", (req, res) => {
	console.warn('/');
	res.sendFile(path.join(__dirname, 'dist', 'index.html'))
})

//读取资源文件
app.use("/assets", express.static(path.join(__dirname, 'dist', 'assets')))


var io
if (process.env.NODE_ENV == 'development') {
	 io = socketIo.listen(http_server);
	 console.warn('仅支持本地电脑的一个浏览器开启窗口输入 http://localhost:4500 进行测试');
	 
} else if (process.env.NODE_ENV == 'production') {
     io = socketIo.listen(https_server);
     console.warn('可以在局域网内的2个电脑之间输入 https://局域网内ip地址:4400 进行测试');

}

const users = {}
const sockS = {}
io.on('connection', (sock) => {
	console.warn('connection');
	/*
	   会议房间模块的socket事件
	**/
	sock.on('join', data => {
		console.warn('join', data);
		console.warn('加入房间以前人员', users[data.roomid]);
		sock.join(data.roomid, () => {
			if (!users[data.roomid]) {
				users[data.roomid] = [];
			}
			let obj = {
				userId: data.userId,
				sockId: sock.id,
				user: data.user,
				videoFlag: data.videoFlag,
				audioFlag: data.audioFlag,
				videoText: data.videoText,
				audioText: data.audioText
			};
			let arr = users[data.roomid].filter(v => v.userId === data.userId);
			if (!arr.length) {
				users[data.roomid].push(obj);
			}
			sockS[data.userId] = sock;
			console.warn('加入房间以后人员', users);

			io.in(data.roomid).emit('joined', users[data.roomid], data.userId); // 发给房间内所有人

		});
	});
	sock.on('offer', data => {
		console.log('offer', data.account);
		sock.to(data.roomid).emit('offer', data);
	});
	sock.on('answer', data => {
		console.log('answer', data.account);
		sock.to(data.roomid).emit('answer', data);
	});
	sock.on('__ice_candidate', data => {
		console.log('__ice_candidate', data.account);
		sock.to(data.roomid).emit('__ice_candidate', data);
	});
	sock.on("disconnection", (data) => {
		console.warn('disconnection--当前断开链接的人员', data);
		
		if (!users[data.roomid]) {
			return
		}
		users[data.roomid] = users[data.roomid].filter(item => {
			return item.userId != data.userId
		});
		let num = users[data.roomid].length
		console.warn('disconnection--用户离开房间后,当前房间的人员', users[data.roomid]);

		//广播给其他用户
		io.in(data.roomid).emit('disconnection', data, num)
	})

	sock.on('disconnect', () => {
		
		console.warn('disconnect', sock.id);

		
		console.warn('sock.adapter.rooms', sock.adapter.rooms);
		let roomId = Object.keys(sock.adapter.rooms)[0]
		console.warn('roomId', roomId);
		if (!users[roomId]) {
			return
		}

		// 存储房间用户数据的对象里面移除该用户的数据
		// 以及获取该用户的数据
		let perData
		users[roomId] = users[roomId].filter(item => {
			if (item.sockId == sock.id) {
				perData = item
			}
			return item.sockId != sock.id
		});
		let num = users[roomId].length

		//广播给其他用户,有时候在推出房间的时候会出现有id,但是无用户的情况，然后导致报错
		console.warn('perData', perData);
		if (!perData) {
			return
		}
		let obj = {
			userId: perData.userId
		}
		io.in(roomId).emit('disconnection', obj, num)

	})

	sock.on('changStatus', data => {
		console.log('changStatus', data);
		console.warn('changStatus--users[data.roomId]', users[data.roomId]);

		users[data.roomId].forEach((item) => {
			if ((item.userId == data.userId) && data.hasOwnProperty("videoFlag")) {
				console.warn('videoFlag');

				item.videoFlag = data.videoFlag

			} else if ((item.userId == data.userId) && data.hasOwnProperty("audioFlag")) {
				console.warn('audioFlag');

				item.audioFlag = data.audioFlag

			}
		});
		console.warn('users[data.roomId]222', users[data.roomId]);
		sock.to(data.roomId).emit('changStatus', data)
	});

	/**
	 * 核心代码模块的socket事件
	 * **/
	sock.on('join_', data => {
		console.warn('sock--join', data);
		sock.join(data.roomid, () => {
			if (!users[data.roomid]) {
				users[data.roomid] = [];
			}
			let obj = {
				account: data.account,
				id: sock.id
			};
			let arr = users[data.roomid].filter(v => v.account === data.account);
			if (!arr.length) {
				users[data.roomid].push(obj);
			}
			sockS[data.account] = sock;
			console.warn('users', users);

			io.in(data.roomid).emit('joined_', users[data.roomid], data.account, sock.id); // 发给房间内所有人
			// sock.to(data.roomid).emit('joined',data.account);
		});
	});
	sock.on('offer_', data => {
		//console.log('offer', data);
		sock.to(data.roomid).emit('offer_', data);
	});
	sock.on('answer_', data => {
		// console.log('answer', data);
		sock.to(data.roomid).emit('answer_', data);
	});
	sock.on('__ice_candidate_', data => {
		// console.log('__ice_candidate', data);
		sock.to(data.roomid).emit('__ice_candidate_', data);
	});
	sock.on("disconnection_", (data) => {
		console.warn('disconnection--data', data);
		io.in(data.roomid).emit('disconnection_', data)
	})
})




